import {getSysUser, login} from '@/api/sys';
import {setToken,getToken} from '@/utils/cookies';
import router from '@/router';
export default {
    namespaced:true,
    state:()=>({
        token:getToken() || '',
        userInfo:{}
    }),
    mutations:{
        setToken(state,token){
            setToken(token);
            state.token = token;
        },
        setUserInfo(state,userInfo){
            state.userInfo = userInfo;
        }
    },
    actions:{
        login({commit},userInfo){
            return new Promise((resolve,reject) => {
                login(userInfo).then(e=>{
                    const {data:{token}} = e;
                    commit('setToken',token);
                    // 跳转登录
                    router.replace('/');
                    resolve(e);
                }).catch(()=>{
                    reject();
                });
            });
        },
        async getUserInfo(context){
            //TODO: 这里要后端返回用户权限以及头像信息
            const res = await getSysUser();
            context.commit('setUserInfo',res);
        },
        logOut({commit}){
            commit('setToken','');
            setToken(null);
            //TODO：有权限之后这里还得清除权限相关
            router.push('/login').then(r => {
                console.log(r);
            });
        }
    }
};